package org.xdj.blue.java.aio.server;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
	
	private AsynchronousSocketChannel channel;
	
	public ReadCompletionHandler(AsynchronousSocketChannel channel) {
		this.channel = channel;
	}

	public void completed(Integer result, ByteBuffer attachment) {
		System.out.println("--ReadCompletionHandler线程名："+Thread.currentThread().getName()+"--");
		attachment.flip();
		byte[] body = new byte[attachment.remaining()];
		attachment.get(body);
		try {
			String req = new String(body, "UTF-8");
			System.out.println("--服务端获取到请求："+req);
			String resp = new SimpleDateFormat("yyy-MM-dd hh:mm:ss:ss").format(new Date()).toString();
			doWrite(resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public void failed(Throwable exc, ByteBuffer attachment) {
		try {
			channel.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void doWrite(String value){
		byte[] bytes = value.getBytes();
		ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
		byteBuffer.put(bytes);
		byteBuffer.flip();
		channel.write(byteBuffer, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {

			public void completed(Integer result, ByteBuffer attachment) {
				if(attachment.hasRemaining()){
					channel.write(attachment, attachment, this);
				}
				
			}

			public void failed(Throwable exc, ByteBuffer attachment) {
				try {
					channel.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
	}
}
